import sensor, image, time, pyb,lcd
from pyb import UART
from pyb import LED
red_threshold = (34,81,9,78,8,73) # red_thresholds 红色阈值
green_threshold  = (36, 53, -35, -14, -7, 5) # green_thresholds 绿色阈值
black_threshold = (0, 10, -3, 3, -5, 5)


sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time = 3000)
sensor.set_auto_gain(False) # must be turned off for color tracking
sensor.set_auto_whitebal(False) # must be turned off for color tracking
#sensor.set_vflip(True)#垂直翻转
#sensor.set_hmirror(True)#水平翻转
r_led = LED(1)
b_led = LED(3)
clock = time.clock()
uart = UART(3, 115200) #打开串口
uart.init(115200, bits=8, parity=None, stop=1) #位宽度参数bits=8，奇偶校验参数parity=None,停止位参数stop=1


# 只有比“pixel_threshold”多的像素和多于“area_threshold”的区域才被
# 下面的“find_blobs”返回。 如果更改相机分辨率，
# 请更改“pixels_threshold”和“area_threshold”。 “merge = True”合并图像中所有重叠的色块。
r=0 #红色
g=0 #绿色
b=0

k=0

while(True):
    clock.tick()
    while True:
        b_led.off()
        img = sensor.snapshot().lens_corr(1.8)
        for blob in img.find_blobs([red_threshold], pixels_threshold=1000, area_threshold=1000):
            img.draw_rectangle(blob.rect())
            img.draw_cross(blob.cx(), blob.cy())
            r=blob.cx() #把红色的x坐标给r
            k=k+1
        print(r)
        for blob in img.find_blobs([green_threshold], pixels_threshold=1000, area_threshold=1000):
            img.draw_rectangle(blob.rect())
            img.draw_cross(blob.cx(), blob.cy())
            g=blob.cx() #把绿色的x坐标给g
            k=k+1
        print(g)
        for blob in img.find_blobs([black_threshold], pixels_threshold=1000, area_threshold=1000, x_stride=100, y_stride=100):
            img.draw_rectangle(blob.rect())
            img.draw_cross(blob.cx(), blob.cy())
            b=blob.cx() #把绿色的x坐标给g
            k=k+1
        print(b)
        lcd.display(img) #在IDE上显示图像
